<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                  <a-input v-model="model.purchaseBill" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep
                    placeholder="请选择申请人"
                    v-model="model.proposer"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departId">
                  <j-select-depart placeholder="请选择申请部门" v-model="model.departId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <template v-if="revokedType">
                <a-divider>作废信息</a-divider>
                <a-col :span="8">
                  <a-form-model-item label="单据名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBillId">
                    <SelectPurchaseCalibrationInput :disabled="formDisabled" v-model="model.purchaseBillId" placeholder="请选择定标结果确认表单" @back="purchaseInfoBack"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationProposer">
                    <select-user-by-dep
                      placeholder="请选择申请人"
                      v-model="model.invalidationProposer" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationDepartId">
                    <j-select-depart placeholder="请选择申请部门" v-model="model.invalidationDepartId" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationCreateTime">
                    <j-date
                      placeholder="请选择申请时间"
                      v-model="model.invalidationCreateTime"
                      :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%"
                      disabled/>
                  </a-form-model-item>
                </a-col>
              </template>
              <!-- <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeId">
                  <select-user-by-dep
                    :tdlx="3"
                    placeholder="请选择申请人"
                    :disabled="formDisabled"
                    @back="backUserInfo"
                    v-model="model.employeeId"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <j-select-depart placeholder="请选择申请单位" :disabled="formDisabled" v-model="model.applicant" />
                </a-form-model-item>
              </a-col> -->
              <!-- 迭代3.2-2删除 -->
              <!-- <a-col :span="8">
                <a-form-model-item label="工期(供货期)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplyTime">
                  <j-date
                    :disabled="formDisabled || revokedType"
                    placeholder="请选择工期"
                    v-model="model.supplyTime"
                    date-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="开标时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="calibrationTime">
                  <j-date
                    date-format="YYYY-MM-DD HH:mm"
                    :disabled="formDisabled || revokedType"
                    placeholder="请选择开标时间"
                    :show-time="true"
                    v-model="model.calibrationTime"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="预算价(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="budget">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.budget"
                    placeholder="请输入预算价"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="中标总价(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalBidPrice">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.totalBidPrice"
                    placeholder="请输入中标总价"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <!-- 迭代3.2-2删除 -->
              <!-- <a-col :span="8">
                <a-form-model-item label="开票方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceManner">
                  <a-input :disabled="formDisabled || revokedType" v-model="model.invoiceManner" placeholder="请输入开票方式" ></a-input>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input :disabled="formDisabled || revokedType" placeholder="请选择所属团队" v-model="model.teamId" :tdlx="3" @back="teamBack"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2">
            <div slot="header">
              <span>招标采购申请信息</span>
              <span style="color: red; font-size: 12px; margin-left:10px;">（注：只可关联一个招标采购申请）</span>
            </div>
            <a-row :gutter="48">
              <ErpPurchaseCalibrationDetailList ref="calibrationDetailList" :disabled="formDisabled || revokedType" :teamId="model.teamId" @onBudget="onBudget" @purchaseInfoBack="purchaseOpinionInfoBack" @isShowBtn="isShowBtn"></ErpPurchaseCalibrationDetailList>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="中标信息">
            <a-row :gutter="48">
              <ErpPurchaseCalibrationUnitList ref="calibrationUnitList" :disabled="formDisabled || revokedType || purchaseOpinionType" @onTotalBidding="onTotalBidding"></ErpPurchaseCalibrationUnitList>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="各厂家报价、谈判情况描述及选定该厂家供货的原因：（重点描述品牌、价格对比情况、原厂还是代理商等）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="quoteDescription">
                  <a-textarea :disabled="formDisabled || revokedType"
                              :max-length="5000"
                              v-model="model.quoteDescription"
                              rows="10"
                              placeholder="重点描述品牌、价格对比情况、是原厂还是代理商等"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="历史采购情况说明：  （重点描述品牌、价格情况）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="historyDescription">
                  <a-textarea
                    :disabled="formDisabled || revokedType"
                    :max-length="1000"
                    v-model="model.historyDescription"
                    rows="10"
                    placeholder="重点描述品牌、价格情况"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="与采购申请的差异：  （重点描述规格型号、参数及品牌、数量等更改项目）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="differenceDescription">
                  <a-textarea
                    :disabled="formDisabled || revokedType"
                    :max-length="1000"
                    v-model="model.differenceDescription"
                    rows="10"
                    placeholder="重点描述规格型号、参数及品牌、数量等更改项目"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="申购单位意见：  （对产品品牌、价格、数量的认可及增减等描述）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="opinionDescription">
                  <a-textarea
                    :disabled="formDisabled || revokedType"
                    :max-length="1000"
                    v-model="model.opinionDescription"
                    rows="10"
                    placeholder="对产品品牌、价格、数量的认可及增减等描述"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled || revokedType" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="4" header="附件信息（1、询比价对比表；2、中标厂家盖章报价单；3、其它）">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!formDisabled || revokedType" :disabled="formDisabled || revokedType" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <a-row :gutter="48" v-if="revokedType">
          <a-col :span="24">
            <a-form-model-item label="作废理由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationReason">
              <a-textarea :max-length="500" :disabled="formDisabled" v-model="model.invalidationReason" rows="4" placeholder="请输入作废理由"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <CommonFirstFlowList v-if="model.bpmStatus !== '1'&&formBpm&&revokedType" :formData="OriginalFormData"></CommonFirstFlowList>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48" v-if="formBpm">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" @click="onPrint">打印</a-button>
      </a-col>
    </a-row>
    <ErpPurchaseCalibrationFormPrint v-if="formBpm" class="print_style" id="calibrationContent" :formData="model" :OriginalFormData="OriginalFormData" :formDataHistory="formData"></ErpPurchaseCalibrationFormPrint>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import ErpPurchaseCalibrationDetailList from './reference/ErpPurchaseCalibrationDetailList'
import ErpPurchaseCalibrationUnitList from './reference/ErpPurchaseCalibrationUnitList'
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import CommonFirstFlowList from '@/views/components/CommonFirstFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpPurchaseCalibrationFormPrint from './ErpPurchaseCalibrationFormPrint' // 打印
import SelectPurchaseCalibrationInput from './SelectPurchaseCalibrationInput'
import Decimal from 'decimal.js'
export default {
    name: 'ErpPurchaseCalibrationForm',
    components: {
      SelectTeamInput,
      ViewFileModal,
      SelectUserByDep,
      SelectPurchaseCalibrationInput,
      ErpPurchaseCalibrationDetailList,
      ErpPurchaseCalibrationUnitList,
      CommonFlowList,
      CommonFirstFlowList,
      ErpPurchaseCalibrationFormPrint
    },
    mixins: [viewFile],
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        activeKey: ['1', '2', '3', '4'],
        OriginalFormData:{},
        model: {
          checkStatus: 0,
          purchaseBill: null,
          purchaseBillId: null,
          invalidationReason: '',
          detailList: [],
          unitList: []
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          // applicant: [
          //     { required: true, message: '请选择申请单位!', trigger: 'change' }
          // ],
          // employeeId: [
          //     { required: true, message: '请选择申请人!', trigger: 'change' }
          // ],
          // departId: [
          //     { required: true, message: '请选择申请部门!', trigger: 'change' }
          // ],
          // 迭代3.2-2删除
          // supplyTime: [
          //     { required: true, message: '请选择工期(供货期)!', trigger: 'change' }
          // ],
          calibrationTime: [
              { required: true, message: '请选择开标时间!', trigger: 'change' }
          ],
          budget: [
              { required: true, message: '请输入预算价!', trigger: 'blur' },
              { pattern: /^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]+\.[0-9]*[1-9][0-9]*)$/, message: '请输入大于0的数字!' },
          ],
          // 迭代3.2-2删除
          // invoiceManner: [
          //     { required: true, message: '请选择开票方式!', trigger: 'blur' }
          // ],
          quoteDescription: [
              { required: true, message: '请输入描述!', trigger: 'blur' }
          ],
          differenceDescription: [
              { required: true, message: '请输入描述', trigger: 'blur' }
          ],
          opinionDescription: [
              { required: true, message: '请输入描述', trigger: 'blur' }
          ],
          teamId: [
              { required: true, message: '请选择所属团队!', trigger: 'change' }
          ],
        },
        url: {
          add: '/api/erp/purchase/procurement/erpPurchaseCalibration/add',
          edit: '/api/erp/purchase/procurement/erpPurchaseCalibration/edit',
          queryById: '/api/erp/purchase/procurement/erpPurchaseCalibration/queryById',
          gainBillNo: "/api/erp/purchase/procurement/erpPurchaseCalibration/gainBillNo",
          queryVerification: '/api/erp/purchase/procurement/erpPurchaseCalibration/referencedVerification',
          queryVerificationCancelling: '/api/erp/purchase/procurement/erpPurchaseCalibration/referencedVerificationCancelling',
          getBizHisProcessNodeInfo: "/api/erpmng/act/process/extActProcessNode/getBizHisProcessNodeInfo",
          queryProvisionBroadList: '/api/erp/purchase/material/erpMaterialCategory/queryAllParent'
        },
        teamIdBackups: null,
        userName: '',
        editCount: 0,
        revokedType: false,
        purchaseOpinionType: false, // 选择定标意见控制中标信息
        purchaseBillIdBackups:null,
        provisionBroadList: [], // 获取采购类型
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    async created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      this.getProvisionBroadList() // 获取采购类型
    },
    methods: {
      ...mapGetters(['userInfo']),
      purchaseInfoBack(item){
        const that = this
        //判断不为空
        if(!!this.model.purchaseBillId && item.length > 0){
          //判断公司是否变化
          // this.purchaseBillIdBackups !== item[0].id
          getAction(this.url.queryVerification,{ id: item[0].id}).then(res => {
            if(res.result == "校验通过"){
              getAction(this.url.queryVerificationCancelling,{ id: item[0].id}).then(response => {
                if(response.result == "校验通过"){
                  //确认后进行改变
                  that.purchaseBillIdBackups = item[0].id
                  that.handleModelData(item[0])
                  that.model.purchaseBillId = item[0].id
                } else {
                  that.$message.warning(response.message)
                  that.model.purchaseBillId = that.purchaseBillIdBackups
                }
              })
            } else {
              that.$message.warning(res.message)
              that.model.purchaseBillId = that.purchaseBillIdBackups
            }
          })
        } else {
          that.handleModelData()
        }
      },
      handleModelData(val){
        if(val){
          // 选择单据 处理原表单数据
          this.$set(this.model,'invalidationPurchaseBill',val.purchaseBill)
          this.$set(this.model,'invalidationProposer',val.proposer)
          this.$set(this.model,'invalidationDepartId',val.departId)
          this.$set(this.model,'invalidationCreateTime',val.createTime)
          this.$set(this.model,'bpmBizTitle','作废-'+ this.userName + '-' + this.model.purchaseBill)
          // this.$set(this.model,'supplyTime',val.supplyTime)
          this.$set(this.model,'calibrationTime',val.calibrationTime)
          this.$set(this.model,'budget',val.budget)
          // this.$set(this.model,'invoiceManner',val.invoiceManner)
          this.$set(this.model,'teamId',val.teamId)
          this.$set(this.model,'quoteDescription',val.quoteDescription)
          this.$set(this.model,'historyDescription',val.historyDescription || '')
          this.$set(this.model,'differenceDescription',val.differenceDescription)
          this.$set(this.model,'opinionDescription',val.opinionDescription)
          this.$set(this.model,'remark',val.remark || '')
          this.$set(this.model,'purchaseFile',val.purchaseFile || '')
          this.$set(this.model,'totalBidPrice',val.totalBidPrice || '')
          this.teamIdBackups = val.teamId
          this.$refs.calibrationUnitList.loadData(1, val.id)
          this.$refs.calibrationDetailList.loadData(1, val.id)
        } else {
          // 选择单据 处理原表单数据
          this.$set(this.model,'invalidationPurchaseBill','')
          this.$set(this.model,'invalidationProposer','')
          this.$set(this.model,'invalidationDepartId','')
          this.$set(this.model,'invalidationCreateTime','')
          // this.$set(this.model,'supplyTime','')
          this.$set(this.model,'calibrationTime','')
          this.$set(this.model,'budget','')
          // this.$set(this.model,'invoiceManner','')
          this.$set(this.model,'teamId','')
          this.$set(this.model,'quoteDescription','')
          this.$set(this.model,'historyDescription','')
          this.$set(this.model,'differenceDescription','')
          this.$set(this.model,'opinionDescription','')
          this.$set(this.model,'remark','')
          this.$set(this.model,'purchaseFile','')
          this.$set(this.model,'totalBidPrice', '')
          this.$refs.calibrationUnitList.dataSource = []
          this.$refs.calibrationDetailList.dataSource = []
        }
        
      },
      getBillNo (params = {}) {
        const that = this
        getAction(this.url.gainBillNo,params).then((res)=>{
          if(res.success){
            that.model.purchaseBill = res.result//单据编号
            if(!that.revokedType){
              that.model.bpmBizTitle = that.userName + '-' + that.model.purchaseBill//标题
            } else {
              that.$set(that.model,'bpmBizTitle','作废-'+ that.userName + '-' + that.model.purchaseBill)
            }
          }
        })
      },
      add (title) {
        this.revokedType = !!title
        if(!!title){
          this.$refs["form"].clearValidate();
          this.model = Object.assign({},{ 
            purchaseBill: '',
            purchaseBillId: '',
            invalidationReason: ''
          })
          this.purchaseBillIdBackups = null
          this.$refs.calibrationUnitList.dataSource = []
          this.$refs.calibrationDetailList.dataSource = []
          this.$refs.calibrationDetailList.showAdd = false
          this.userName = this.userInfo().empName;// 当前登录人名称
          this.model.proposer = this.userInfo().empId; // 当前登录人
          this.model.departId = this.userInfo().deptId; //当前登录人部门
          this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
          this.getBillNo({type: '2'}) //获取单据编号
          this.validatorRules = {
            purchaseBillId: [
              { required: true, message: '请选择单据名称!', trigger: 'change' }
            ],
            invalidationReason: [
              { required: true, message: '请输入作废理由!', trigger: 'blur' },
            ]
          }
        } else {
          this.edit(this.modelDefault);
          this.userName = this.userInfo().empName;// 当前登录人名称
          this.model.proposer = this.userInfo().empId; // 当前登录人
          this.model.departId = this.userInfo().deptId; //当前登录人部门
          this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
          this.getBillNo() //获取单据编号
        }
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        this.revokedType = this.model.purchaseBill?this.model.purchaseBill.substring(0,2) == 'ZF':false
        if(this.revokedType){
          this.validatorRules = {
            purchaseBillId: [
              { required: true, message: '请选择单据名称!', trigger: 'change' }
            ],
            invalidationReason: [
              { required: true, message: '请输入作废理由!', trigger: 'blur' },
            ]
          }
        } else {
          this.validatorRules = {
            // supplyTime: [
            //   { required: true, message: '请选择工期(供货期)!', trigger: 'change' }
            // ],
            calibrationTime: [
              { required: true, message: '请选择开标时间!', trigger: 'change' }
            ],
            budget: [
              { required: true, message: '请输入预算价!', trigger: 'blur' },
              { pattern: /^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]+\.[0-9]*[1-9][0-9]*)$/, message: '请输入大于0的数字!' },
            ],
            // invoiceManner: [
            //   { required: true, message: '请选择开票方式!', trigger: 'blur' }
            // ],
            quoteDescription: [
              { required: true, message: '请输入描述!', trigger: 'blur' }
            ],
            differenceDescription: [
              { required: true, message: '请输入描述', trigger: 'blur' }
            ],
            opinionDescription: [
            { required: true, message: '请输入描述', trigger: 'blur' }
            ],
            teamId: [
              { required: true, message: '请选择所属团队!', trigger: 'change' }
            ]
          }
        }
        this.editCount = 0
        if (this.formBpm === true) {
          getAction(this.url.getBizHisProcessNodeInfo, { flowCode: 'onl_erp_purchase_calibration', dataId: this.model.purchaseBillId }).then((res) => {
            if (res.success) {
              var data = {
                dataId: res.result.dataId,
                procInsId: res.result.procInsId,
                tableName: res.result.tableName,
                vars: res.result.records
              }
              this.OriginalFormData = data;
            }
          })
        }
        this.visible = true;
        if (this.model.id) {
          this.teamIdBackups = this.model.teamId
          this.$refs.calibrationDetailList.loadData(1,  this.revokedType?this.model.purchaseBillId:this.model.id)
          this.$refs.calibrationUnitList.loadData(1, this.revokedType?this.model.purchaseBillId:this.model.id)
          // 升级版迭代1判断是否有项目id，有则显示新增按钮，没有则隐藏新增按钮
          // this.$refs.calibrationDetailList.showAdd = true // 显示隐藏新增按钮
        } else {
          this.$refs.calibrationUnitList.dataSource = []
          this.$refs.calibrationDetailList.dataSource = []
          this.$refs.calibrationDetailList.showAdd = false
        }
      },
      teamBack(item) {
        //判断不为空
        if(!!this.model.teamId && item.length > 0) {
          //判断团队是否变化
          if(this.teamIdBackups !== item[0].id) {
            let detailList = this.$refs.calibrationDetailList.submitForm()
            if(detailList.length > 0) {
              const that = this;
              that.$confirm({
                title: "是否确认",
                content: "是否确认切换所属团队，此操作将会清空招标采购申请信息明细中已填写的所有信息？",
                onOk() {
                  //确认后进行改变
                  that.teamIdBackups = that.model.teamId
                  //清空子表数据
                  that.$refs.calibrationDetailList.dataSource = []
                  that.$refs.calibrationDetailList.showAdd = false
                  
                  if (that.purchaseOpinionType) {
                    that.purchaseOpinionType = false
                    that.$refs.calibrationUnitList.dataSource = []
                    that.onTotalBidding([])
                  }
                },
                onCancel() {
                  that.model.teamId = that.teamIdBackups
                }
              });
            } else {
              this.teamIdBackups = item[0].id
            }
          }
        }
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      // 获取预算价
      onBudget (value) {
        if(this.editCount==0){
          this.editCount = 1
        } else {
          this.$set(this.model, 'budget', value || '0')
        }
      },
      // 第一次加载的时候判断中标信息是否有按钮
      isShowBtn (value) {
        this.purchaseOpinionType = value
      },
      // 获取定标意见单数据
      purchaseOpinionInfoBack (data) {
        // this.purchaseOpinionInfoData = data // 定标意见单数据
        if (!data) {
          // 清除数据
          this.$refs.calibrationUnitList.dataSource = []
          this.purchaseOpinionType = false
          this.onTotalBidding([])
          return false
        }
        let params = {
          column: 'createTime',
					order: 'desc',
					pageNo: 1,
					pageSize: 100,
					billId: data
        }
        getAction('/api/erp/purchase/procurement/erpPurchaseCalibrationOptionUnit/allList', params).then(res => {
          if (res.success) {
            this.$refs.calibrationUnitList.dataSource = res.result.records
            this.purchaseOpinionType = true
            this.onTotalBidding(res.result.records)
          } else {
            this.purchaseOpinionType = true
          }
        }).catch(err => {
          this.purchaseOpinionType = false
          this.$message.error(err.message)
        })
      },
      onTotalBidding (arr) {
        if (arr && arr.length) {
          let totalBidPrice = new Decimal(0)
          arr.forEach(item => {
            totalBidPrice = totalBidPrice.add(new Decimal(item.bidding || 0))
          })
          this.$set(this.model, 'totalBidPrice', Number(totalBidPrice))
        } else {
          this.$set(this.model, 'totalBidPrice', '0')
        }
      },
      // 获取采购类型
      getProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            that.provisionBroadList = res.result
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      validateForm () {
        var that = this
        that.$emit('unButtonDisable');
        return this.$refs.form.validate().then(async valid => {
        let detailList = this.$refs.calibrationDetailList.submitForm()
          let unitList = this.$refs.calibrationUnitList.submitForm()
          if (!detailList.length > 0) {
            this.$message.warning('请添加招标采购申请信息！');
            return Promise.reject('请添加招标采购申请信息！')
          }
          if (!unitList.length > 0) {
            this.$message.warning('请添加中标信息！');
            return Promise.reject('请添加中标信息！')
          }
          if(this.revokedType){
            let res = await getAction(this.url.queryVerification,{id: that.model.purchaseBillId})
            if (res.success) {
              let res1 = await getAction(this.url.queryVerificationCancelling,{id: that.model.purchaseBillId})
              if (res1.success) {
                return Promise.resolve()
              } else {
                this.$message.warning(res1.message);
                return Promise.reject(res1.message)
              }
            } else {
              this.$message.warning(res.message);
              return Promise.reject(res.message)
            }
          } else {
            // 不是作废定标结果确认单
            // 当选择了定标意见单时，则不需要做校验
            if (!detailList[0].opinionId) {
              let judgeType = await getAction('/api/erp/purchase/procurement/erpPurchaseApplyInvitation/queryById', {id: detailList[0].invitationId}) // 判断类型
              if (judgeType.success) {
                // 判断采购类型
                if (this.provisionBroadList && this.provisionBroadList.length > 0) {
                  let categoryCode = ''
                  this.provisionBroadList.forEach(item => {
                    if (item.id === detailList[0].provisionBroad) {
                      categoryCode = item.categoryCode
                    }
                  })
                  var totalBidPrice = new Decimal(0)
                  if (unitList && unitList.length > 0) {
                    unitList.forEach(item => {
                      // 计算中标金额之和
                      totalBidPrice = totalBidPrice.add(new Decimal(item.bidding || 0))
                    })
                  }
                  // 采购类型是行政类，中标金额需要超过十万元
                  if (categoryCode == '01' || judgeType.result.provisionBroadType == 'administration') {
                    if (Number(totalBidPrice) >= 100000) {
                      // 小于十万则终止提交
                      this.$message.warning('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程');
                      return Promise.reject('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
                    }
                  }
                  if (categoryCode == '02' || judgeType.result.provisionBroadType == 'business') {
                    // 采购类型是业务类，中标金额再根据业务分类判断
                    if (detailList[0].businessSegment == 'HBZXYWBKFZR') {
                      // 环保咨询
                      if (Number(totalBidPrice) >= 100000) {
                        // 小于十万则终止提交
                        this.$message.warning('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程');
                        return Promise.reject('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
                      }
                    } else if (detailList[0].businessSegment == 'ZLYWYWBKFZR') {
                      // 工程运维
                      if (Number(totalBidPrice) >= 200000) {
                        // 小于二十万则终止提交
                        this.$message.warning('当前中标总金额超过标准金额200000元，请先发起“定标意见单”流程');
                        return Promise.reject('当前中标总金额超过标准金额200000元，请先发起“定标意见单”流程')
                      }
                    } else if (detailList[0].businessSegment == 'JYJCYWBKFZR') {
                      // 检验检测
                      if (Number(totalBidPrice) >= 100000) {
                        // 小于十万则终止提交
                        this.$message.warning('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程');
                        return Promise.reject('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
                      }
                    } else if (detailList[0].businessSegment == 'SZXXYWBKFZR') {
                      // 数字信息
                      if (Number(totalBidPrice) >= 200000) {
                        // 小于二十万则终止提交
                        this.$message.warning('当前中标总金额超过标准金额200000元，请先发起“定标意见单”流程');
                        return Promise.reject('当前中标总金额超过标准金额200000元，请先发起“定标意见单”流程')
                      }
                    } else if (detailList[0].businessSegment == 'HBGJYWBKFZR') {
                      // 智慧管家
                      if (Number(totalBidPrice) >= 100000000) {
                        // 小于1000万则终止提交
                        this.$message.warning('当前中标总金额超过标准金额100000000元，请先发起“定标意见单”流程');
                        return Promise.reject('当前中标总金额超过标准金额100000000元，请先发起“定标意见单”流程')
                      }
                    } else if (detailList[0].businessSegment == 'LTYWYWBKFZR') {
                      // 林碳业务
                      if (Number(totalBidPrice) >= 100000) {
                        // 小于十万则终止提交
                        this.$message.warning('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程');
                        return Promise.reject('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
                      }
                    } else if (detailList[0].businessSegment == 'SLYWYWBKFZR') {
                      // 水利业务
                      if (Number(totalBidPrice) >= 100000000) {
                        // 小于1000万则终止提交
                        this.$message.warning('当前中标总金额超过标准金额100000000元，请先发起“定标意见单”流程');
                        return Promise.reject('当前中标总金额超过标准金额100000000元，请先发起“定标意见单”流程')
                      }
                    }
                  }
                }
              }
            }
          }
        })
      },
      async submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          // 触发表单验证
          await this.validateForm()
          that.submit(type)
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        let detailList = this.$refs.calibrationDetailList.submitForm() || []
        let unitList = this.$refs.calibrationUnitList.submitForm() || []
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        this.model.detailList = detailList
        this.model.unitList = unitList
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#calibrationContent',
          popTitle: '定标结果确认详情 · 禾美环保',
          endCallback() {

          }
        })
      }
      // backUserInfo(data) {
      //   this.model.applicant = data[0].orgDepart;//申请人单位
      //   this.model.departId = data[0].departmentId;//申请人部门
      // }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>